$(function() { 	
	$("#editBtn").attr("disabled",true);
	$("input[name='icon']").focus(function() {
        $(".icon-drop").show();
    });
	$("#menuForm").click(function(event) {
	    var obj = event.srcElement || event.target;
	    if (!$(obj).is("input[name='icon']")) {
	    	$(".icon-drop").hide();
	    }
	});
	$(".icon-drop").find(".ico-list i").on("click", function() {
		$('#icon').val($(this).attr('class'));
    });
	
	//下拉框初始化
	$("#menuType").append("<option value='M'>"+"目录"+"</option>");
	$("#menuType").append("<option value='C'>"+"菜单"+"</option>");
	$("#menuType").append("<option value='F'>"+"按钮"+"</option>");
});
var treeTable = $('#demo').bootstrapTreeTable({
			toolbar: "#demo-toolbar",    //顶部工具条
			expandColumn : 1,            // 在哪一列上面显示展开按钮
			url: "/menu/list",
			height:445,
			ajaxParams:{}, 
			id: "menuId",
			parentId: "parentId",
			uniqueId: "menuId",
			expandAll: false,
			expandFirst: true,
			showColumns: false, 
			showRefresh: false,
			singleSelect: true,
			expanderExpandedClass: 'fa fa-angle-down fa-lg',       // 展开的按钮的图标
			expanderCollapsedClass: 'fa fa-angle-right fa-lg',     // 缩起的按钮的图标
                  columns: [{
                      radio: true,
                      width:'20'
                   },{
                	   width: '60',
                	   field:'',
                	   title:'伸/缩',
               		   halign:"center",
                   },{
                	   title:'序号',
                	   field:'orderNum',
               		   halign:"center",
                       width: '40',
                       align: "center",
                       formatter: function(value,row, index) {
                           return '<span class="badge" style="background: #5cb85c;">'+row.orderNum+'</span>'
                       }
                       
                   },{
                      title: '资源名称',
                      field: 'menuName',
                      align: "center",
                      width: '120',
                      formatter: function(value,row, index) {
                              return row.menuName;
                      }
                  },
                  {
                      field: 'menuId',
                      title: '主键',
                      width: '150',
                      align: "left",
                      visible: false
                  },
                  {
                      title: '类型',
                      field: 'menuType',
                      halign:"center",
                      width: '60',
                      align: "center",
                      valign: "top",
                       formatter: function(value,item, index) {
                          if (item.menuType == 'M') {
                              return '<span class="label label-success">目录</span>';
                          }
                          else if (item.menuType == 'C') {
                              return '<span class="label label-success">菜单</span>';
                          }
                          else if (item.menuType == 'F') {
                              return '<span class="label label-success">按钮</span>';
                          }
                      } 
                  },{
                      field: 'url',
                      title: '请求地址',
                      width: '150',
                      align: "left"
                  },{
                      field: 'icon',
                      halign :"center",
                      title: '图标样式',
                      width: '110',
                      align: "center",
                      formatter: function(value,row, index) {
                          return value;
                      }
                  },{
                      field: 'perms',
                      halign:"center",
                      title: '权限标识',
                      width: '150',
                      align: "center",
                  },{
                      title: '操作',
                      halign:"center",
                      width: '180',
                      align: "center",
                      formatter: function(value,row, index) {
                    	  if(row.menuId!='i'){//首页不可操作
                    		  var actions = [];
                    		  var param=row.menuId+"|"+row.parentId+"|"+row.orderNum;
                    		  if($("#menu-move").val()){
                    			  actions.push('<a class="btn btn-success btn-xs" id='+row.menuId+' onclick=onClick("'+param+'|up'+'")><i class="fa fa-long-arrow-up"></i>上移</a>');
                    			  actions.push('<a class="btn btn-success btn-xs" id='+row.menuId+' onclick=onClick("'+param+'|down'+'")><i class="fa fa-long-arrow-down"></i>下移</a>');
                    		  }
                    		  if($("#menu-remove").val()){
                    			  actions.push('<a class="btn btn-success btn-xs" id='+row.menuId+' onclick=onClick("'+ row.menuId +'")><i class="fa fa-trash-o"></i>删除</a>');
                    		  }	
                    		  return actions.join(' ');
                    	  }
                      }
                  }],
                  onAll: function(data) {
                      return false;
                  },
                  onLoadSuccess: function(data) {
                      return false;
                  },
                  onLoadError: function(status) {
                      return false;
                  },
                  onClickCell: function(field, value, row, $element) {
                      console.log("onClickCell",row);
                      return false;
                  },
                  onDblClickCell: function(field, value, row, $element) {
                      console.log("onDblClickCell",row);
                      return false;
                  },
                  onClickRow: function(row, $element) {
                	  if(row.menuId!='i'){
                		  $("#editBtn").removeAttr("disabled");
                	  }else{
                		  $("#editBtn").attr("disabled",true);
                	  }
                      return false;
                  },
                  onDblClickRow: function(row, $element) {
                      //双击查看
                	  $("#menuId").val(row.menuId);
                	  $("#menuType").selectpicker('val',row.menuType);
                	  $("#menuName").val(row.menuName);
                	  $("#parentId").val(row.parentId);//回显时父级ID赋值
                	  $("#parentName").val(row.parentName==null?'首页':row.parentName);//回显上级资源名称
                	  $("#icon").val(row.icon);
                	  $("#url").val(row.url);
                	  $("#perms").val(row.perms);
                	  $("#orderNum").val(row.orderNum);
                      //弹出模态框
                      $("#menuModal").modal();
                      //设置表头
                      $("#menuModal").find('.modal-title').text('查看菜单信息')
                      var form = document.forms[0];
                      for ( var i = 0; i < form.length; i++) { 
                		  var element = form.elements[i]; 
                		  if(element.id != "close"){
                			  element.disabled = "true"; 
                		  }
                      }
                  }
              	});
              $("#selectBtn").click(function(){
                  var selecteds = $('#demo').bootstrapTreeTable('getSelections');
                  $.each(selecteds,function(_i,_item){
                      console.log(_item);
                  });
                  alert("看console");
              })
              $("#editBtn").click(function(){
            	  noDisable();
            	  var row=$("#demo").bootstrapTreeTable('getSelections')[0];//获取选中行数据
            	  if(!row){
            		  return;
            	  }
            	  $("#menuId").val(row.menuId);
            	  $("#menuType").selectpicker('val',row.menuType);
            	  $("#menuName").val(row.menuName);
            	  $("#parentId").val(row.parentId);//回显时父级ID赋值
            	  $("#parentName").val(row.parentName==null?'首页':row.parentName);//回显上级资源名称
            	  $("#icon").val(row.icon);
            	  $("#url").val(row.url);
            	  $("#perms").val(row.perms);
            	  $("#orderNum").val(row.orderNum);
            	  $("#menuType").attr("disabled",true);
                  //弹出模态框
                  $("#menuModal").modal();
                  //设置表头
                  $("#menuModal").find('.modal-title').text('编辑菜单信息')
              })
              $("#addBtn").click(function(){//新增菜单*******************************
                  //新增、编辑、查看公用一个模态框。所以需要初始化清空表单
            	  noDisable();
            	  $("#menuId").val("");
            	  $("#menuForm")[0].reset();
            	  $("#menuType").selectpicker('val',"");
            	  $("#menuType").attr("disabled",true);
                  //弹出模态框
                  $("#menuModal").modal();
                  //设置表头
                  $("#menuModal").find('.modal-title').text('新增菜单信息')
              })
              $("#expandRowBtn").click(function(){
                  $('#demo').bootstrapTreeTable('toggleRow',1);
              })
              var _expandFlag_all = false;
              $("#expandAllBtn").click(function(){
                  if(!_expandFlag_all){
                      $('#demo').bootstrapTreeTable('expandAll');
                      _expandFlag_all = true;
                  }else{
                      $('#demo').bootstrapTreeTable('collapseAll');
                      _expandFlag_all = false;
                  }
              })
              var _showFlag = true;
              $("#showColumnBtn").click(function(){
                  if(_showFlag){
                      $('#demo').bootstrapTreeTable('hideColumn',"orderNum");
                  }else{
                      $('#demo').bootstrapTreeTable('showColumn',"orderNum");
                  }
                  _showFlag = _showFlag?false:true;
              })
              $("#destroyBtn").click(function(){
                  $('#demo').bootstrapTreeTable('destroy');
              })
              
              //上下移动、删除
              function onClick(e){
              	var params=[];
              	var mid,pid,lev,mf;
              	if(e.indexOf("|")!=-1){
              		params=e.split("|");
              		mid=params[0];//菜单id
              		pid=params[1];//父级id
              		lev=params[2];//当前排序号
              		mf=params[3];//上下移标识
  					//后台上下移动
  				    $.ajax({
  				        url: "/menu/moveUp",
  				        method:"post",
  				        dataType: 'json',
  				        contentType:"application/json",
  				        data:JSON.stringify({moveFlag:mf,menuId:mid,parentId:pid,orderNum:lev}),
  				        success: function (result) {
  					        if(result.success){
		                		$('#demo').bootstrapTreeTable('refresh');
		                		$("#editBtn").attr("disabled",true);
		                		//选中(未找到解决方案)

  				        	}else{
  				        		if(mf=='up'){
  				        			layer.msg("当前节点不可上移!");
  				        		}else{
  				        			layer.msg("当前节点不可下移!");
  				        		}
  				        	}
  						}
  					});
              	}else{//删除
              		 layer.confirm('删除该目录以及子目录？',{title:"确认"},function(rt){
	  				    $.ajax({
	  				        url: "/menu/removeMenu?menuId="+e,
	  				        method:"get",
	  				        dataType: 'json',
	  				        success: function (result) {
	  					        if(result.success){
			                		$('#demo').bootstrapTreeTable('refresh');
			                		$("#editBtn").attr("disabled",true);
			                		//涉及权限问题不直接刷新
	  					        	/*toastr.info("你已成功删除部分【目录/菜单】！即将刷新浏览器!","提示");
	  					        	setTimeout(function() {
	  					        		parent.location.reload();  
	  					          	}, 3000);*/
			                		layer.msg("删除成功!");
	  				        	}
	  						}
	  					});
                     },function(index){layer.close(index);})
              	}
              }

              $("#addOreditBtn").on('click',function(){
            	  $("#menuType").removeAttr("disabled");//提交时去除样式，不然取不到值
            	  data=$('#menuForm').serialize();
            	  if($("#menuId").val()){//编辑
            		  var checkRow;
            		  checkRow=$("#demo").bootstrapTreeTable('getSelections')[0];//获取选中行数据
	            	  $.ajax({ 
	            		  type:'post',  
	            		  url:"/menu/editMenu", 
	            		  data:data,  
	            		  dataType:'json',
	            		  success:function(data){
	            			  if(data.success){
	            				  $('#menuModal').modal('hide');
	            				  $('#demo').bootstrapTreeTable('refresh');
	            				  $("#editBtn").attr("disabled",true);
	            				  if(checkRow.menuType != 'F'){
	            					  layer.msg("修改成功：刷新浏览器后生效!");
	            				  }else{
	            					  layer.msg("修改成功!");
	            				  }
	            			  }
	            		  }
	            	  })
            	  }else{//新增
	            	  $.ajax({ 
	            		  type:'post',  
	            		  url:"/menu/saveMenu", 
	            		  data:data,  
	            		  dataType:'json',
	            		  success:function(data){
	            			  if(data.success){
	            				  $('#menuModal').modal('hide');
	            				  $('#demo').bootstrapTreeTable('refresh');
	            				  $("#editBtn").attr("disabled",true);
	            			  }
	            		  }
	            	  })
            	  }
              })
/*****************************************************选择父级目录树*************************/
	var setting = {
			view: {
				selectedMulti: true,
				showIcon: false
			},
			check: {
				chkStyle: "radio",
				enable: true,
				radioType: "all"
			},
			data: {
	            key: {
	                children: "childs",
	                name: "menuName",
	            },
				simpleData: {
					enable: true,
	                idKey: "menuId",
	                pIdKey: "parentId", 
	                rootPId:null
				}
			},
			callback: { 
			 	onClick: function (e, treeId, treeNode, clickFlag) { //单击选中节点
			 		$.fn.zTree.getZTreeObj(treeId).checkNode(treeNode, !treeNode.checked, true); 
			 	}, 
			 	beforeExpand: function(treeId,currNode){
					var cLevel = currNode.level;
					//这里假设id是唯一的
					var cId = currNode.menuId;
					//此对象可以保存起来，没有必要每次查找
					var treeObj = $.fn.zTree.getZTreeObj("parentTree");
					//展开的所有节点，这是从父节点开始查找（也可以全文查找）
					var expandedNodes = treeObj.getNodesByParam("open", true, currNode.getParentNode());
					for(var i = expandedNodes.length - 1; i >= 0; i--){
						var node = expandedNodes[i];
						var level = node.level;
						var menuId = node.menuId;
						if (cId != menuId && level == cLevel) {
							treeObj.expandNode(node, false);
						}
					}
			 	},beforeCheck : function(treeId, treeNode, clickFlag){
			 		//智能选中叶子节点
					return true;
				}
			}
		};
          function selectMenuTree() {
        	  layui.use(['layer'],function () {
        		  var layer = layui.layer,$=layui.$;
        		  layer.open({
            		  type:1,//类型
	                  area:['300px','450px'],//定义宽和高
	                  title:'选择父级目录',//题目
	                  shadeClose:true,//点击遮罩层关闭
	                  content: $('#pMenuTree'),//打开的内容
	                  btn: ['确定']//按钮
	                  ,yes: function(index, layero){//确定按钮回调,
	                	  //去选中节点信息
	                	  var node= $.fn.zTree.getZTreeObj("parentTree").getCheckedNodes()[0];
	                	  var menutype;
	                	  if(node.level=='0'){
	                		  menutype='M';
	                	  }else if(node.level=='1'){
	                		  menutype='C';
	                	  }else{
	                		  menutype='F';
	                	  }
	                	  $("#parentName").val(node.menuName);
	                	  $("#parentId").val(node.menuId);
	                	  $("#menuType").selectpicker('val',menutype);
	                	  layer.closeAll("page");//关闭模态框
	                  },btnAlign: 'c',
	                  success: function(layero, index){ //打开模态框后的回调：初始化
		  	          		$.ajax({
			          	        url: "/menu/list?menuType=MC",
			          	        cache: false,
			          	        dataType: 'json',
			          	        success: function (result) {
			          		        /*if(result.success){*/
			          		       /* datas=result.data;*/
			          	        	datas=result;
			          				$(document).ready(function(){
			          					$.fn.zTree.init($("#parentTree"),setting,datas);//.expandAll(false);
			          		            var menuTree = $.fn.zTree.getZTreeObj("parentTree");
			          		            var nodes = menuTree.getNodes();
			          		            for (var i = 0; i < nodes.length; i++) { //设置节点展开
			          		            	menuTree.expandNode(nodes[i], true, false, true);
			          		            	menuTree.expandNode(nodes[i].childs[0], true, false, true);
			          		            }
			          				});
			          		        /*}*/
			          	        }
			          		}); 
	                   }
                  });
              })

	       }       
          
        //取消表单不可编辑 
        function noDisable() { 
          var form = document.forms[0]; 
          for ( var i = 0; i < form.length; i++) { 
          var element = form.elements[i]; 
	          if(element.disabled){
	        	  element.disabled = false; 
	          }
          } 
       } 
        //右上角模糊查询
        function selectByKey(){
        	$("#demo").bootstrapTreeTable('refresh',{menuName:$("#search_key").val()});
        	$('#demo').bootstrapTreeTable('expandAll');
        }